package org.dolphin.dao.impl;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import org.dolphin.dao.DistrictDao;
import org.dolphin.dao.util.SessionHelper;
import org.dolphin.entity.district.City;
import org.dolphin.entity.district.Region;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "districtDao")
public class DistrictDaoImpl implements DistrictDao {
  @Autowired(required = true)
  private SessionFactory sessionFactory;

  @SuppressWarnings("unchecked")
  @Override
  public List<City> getCities(List<Long> regions) {
    if (regions == null || regions.isEmpty()) {
      return Collections.emptyList();
    }
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = session.createCriteria(City.class);
    criteria.add(Restrictions.in("region.id", regions));
    criteria.addOrder(Order.asc("name"));
    List<City> list = criteria.list();
    return list;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<Region> getRegions() {
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = session.createCriteria(Region.class);
    criteria.addOrder(Order.asc("name"));
    List<Region> list = criteria.list();
    return list;
  }

  @Override
  public City loadCity(Serializable id) {
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    City city = (City) session.load(City.class, id);
    return city;
  }
}
